package org.looom.orglooomschool;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity8 extends AppCompatActivity {

    private TextView rightText, leftText;

    public static final String ACTION_EAT = "com.example.ACTION_EAT";

    private BroadcastReceiver eatReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 左侧收到广播，2秒后显示文字
            new Handler().postDelayed(() -> leftText.setText("开饭了"), 2000);
        }
    };

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity8);

        rightText = findViewById(R.id.right_text);
        leftText = findViewById(R.id.left_text);

        // 注册广播接收器
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(eatReceiver, new IntentFilter(ACTION_EAT), Context.RECEIVER_EXPORTED);
        } else {
            registerReceiver(eatReceiver, new IntentFilter(ACTION_EAT));
        }


        // 3秒后右边显示文字并发送广播
        new Handler().postDelayed(() -> {
            rightText.setText("开饭了");

            // 发送广播
            Intent intent = new Intent(ACTION_EAT);
            sendBroadcast(intent);

        }, 3000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(eatReceiver);
    }
}